package com.czl.module_service.fragment.assetHandle

import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.czl.base.base.BaseFragment
import com.czl.base.config.AppConstants
import com.czl.base.data.bean.tengyun.*
import com.czl.base.event.LiveBusCenter
import com.czl.base.util.ChoiceImgHelper
import com.czl.module_service.BR
import com.czl.module_service.R
import com.czl.module_service.adapter.AssetHandleAddFacilityAdapter
import com.czl.module_service.adapter.AssetHandleApplyCardLowerInfoAdapter
import com.czl.module_service.databinding.*
import com.czl.module_service.view.ListSheetDialogFragment
import com.czl.module_service.viewmodel.AssetHandleApplyAddViewModel
import com.czl.module_service.viewmodel.PurchaseApplyAddViewModel
import java.math.BigDecimal

@Route(path = AppConstants.Router.Service.F_SERVICE_ASSET_HANDLE_APPLY_ADD)
class AssetHandleApplyAddFragment :
    BaseFragment<FragmentAssetHandleApplyAddBinding, AssetHandleApplyAddViewModel>() {

    //    val list : MutableList<AssetHandleFacilityBean> = arrayListOf()
    val ownerCompanyList: MutableList<CompanyBean> = arrayListOf()
    val ownerCompanyNameList: MutableList<String> = arrayListOf()

    override fun initContentView(): Int {
        return R.layout.fragment_asset_handle_apply_add
    }

    private val mAdapter: AssetHandleAddFacilityAdapter by lazy {
        AssetHandleAddFacilityAdapter(this).apply {
            val headerBinding = FragmentAssetHandleApplyAddHeaderBinding.inflate(layoutInflater)
            val footerBinding = FragmentAssetHandleApplyAddFooterBinding.inflate(layoutInflater)
            headerBinding.setVariable(initVariableId(), viewModel)
            addHeaderView(headerBinding.root)
            footerBinding.setVariable(initVariableId(), viewModel)
            addFooterView(footerBinding.root)
        }
    }
    private val lowerAdapter: AssetHandleApplyCardLowerInfoAdapter by lazy {
        AssetHandleApplyCardLowerInfoAdapter(this)
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun useBaseLayout(): Boolean {
        return false

    }

    override fun initData() {
        super.initData()
        initAdapter()
        initLowerAdapter()
        viewModel.getCompanyList()
    }

    private fun initAdapter() {
        binding.ryCommon.run {
            adapter = mAdapter
        }
    }
    fun initLowerAdapter () {
//        lowerAdapter.setListData(arrayListOf(), true)
        binding.expandableListView.setAdapter(lowerAdapter)

        val headerBinding = FragmentAssetHandleApplyAddHeaderBinding.inflate(layoutInflater)
        val footerBinding = FragmentAssetHandleApplyAddFooterBinding.inflate(layoutInflater)
        headerBinding.setVariable(initVariableId(), viewModel)
        headerBinding.facilityNum.visibility = View.GONE
        binding.expandableListView.addHeaderView(headerBinding.root)
        footerBinding.setVariable(initVariableId(), viewModel)
        binding.expandableListView.addFooterView(footerBinding.root)
//        binding.expandableListView.visibility = View.GONE
    }

    override fun initViewObservable() {
        LiveBusCenter.observeAddAssetHanldeFacilityEvent(this, {
            if (it.data != null) {
                // 选中的物品添加
//                binding.expandableListView.visibility = View.GONE
                viewModel.facilityList.addAll(it.data!!)
                mAdapter.setList(viewModel.facilityList)
                setFacilityIdList()
            }
        })
        // viewModel中选择附件
        viewModel.uc.choiceImgEvent.observe(this, {
            ChoiceImgHelper.ChoiceImg(this,
                { result -> result[0]?.let { t -> viewModel.uploadHeadImg(t.compressPath, it) } },
                {})
        })
        // adapter中选择附件
        viewModel.uc.choiceAdapterFileEvent.observe(this, {
            val bean = mAdapter.data[mAdapter.position]
            bean.fileUrl = it.url
            val fileBean = FileBean()
            fileBean.name = it.name
            fileBean.fileName = it.name
            fileBean.url = it.url
            fileBean.fileUrl = it.url
            fileBean.userName = viewModel.model.getLoginName()
            fileBean.tname = viewModel.model.getLoginName()
            val list :  MutableList<FileBean> = arrayListOf()
            list.add(fileBean)
            bean.fileList = list
            mAdapter.setData(mAdapter.position, bean)
        })
        LiveBusCenter.observeAddAssetHanldeSortEvent(this, {
            if (it.data != null) {
                // 选中的物品添加
                if (it.handleType == "inuse") {
                    var inUseLowerList: MutableList<AssetHandleSortBean> = arrayListOf()
                    for (bean in it.data!!) {
                        if (bean.manageMode == 1) {
                            viewModel.inUseProductList.add(bean)
                        } else {
                            inUseLowerList.add(bean)
                        }
                    }
                    viewModel.inUseLowerList = inUseLowerList
                } else if (it.handleType == "store") {
                    var inStoreLowerStoreList: MutableList<AssetHandleSortBean> = arrayListOf()
                    for (bean in it.data!!) {
                        if (bean.manageMode == 1) {
                            viewModel.inStoreProductList.add(bean)
                        } else {
                            inStoreLowerStoreList.add(bean)
                        }
                    }
                    if (!inStoreLowerStoreList.isEmpty()){
                        addInStoreSortInfo(inStoreLowerStoreList)
                    }
                } else if (it.handleType == "damage") {
                    var inStoreLowerDamageList: MutableList<AssetHandleSortBean> = arrayListOf()
                    for (bean in it.data!!) {
                        if (bean.manageMode == 1) {
                            var locationDesc = "丢失"
                            if(bean.storehouseLocatId != null && bean.storehouseLocatId!! > 0) {
                                locationDesc = bean.storehouseLocatName + "-坏"
                            }
                            bean.locationDesc = locationDesc
                            viewModel.inStoreProductList.add(bean)
                        } else {
                            inStoreLowerDamageList.add(bean)
                        }
                    }
                    if (!inStoreLowerDamageList.isEmpty()){
                        addDamageSortInfo(inStoreLowerDamageList)
                    }
                } else if (it.handleType == "inven") {
                    var inStoreLowerInvenList: MutableList<AssetHandleSortBean> = arrayListOf()
                    for (bean in it.data!!) {
                        if (bean.manageMode == 1) {
                            viewModel.inStoreProductList.add(bean)
                        } else {
                            inStoreLowerInvenList.add(bean)
                        }
                    }
                    if (!inStoreLowerInvenList.isEmpty()){
                        addDamageSortInfo(inStoreLowerInvenList)
                    }
                }
                setProductIdList()
                setSortIdInfoList()
//                binding.ryCommon.visibility = View.GONE
                var newBean = AssetHandleBean()
                newBean.inUseProductList = viewModel.inUseProductList
                newBean.inUseLowerList = viewModel.inUseLowerList
                newBean.inStroreProductList = viewModel.inStoreProductList
                newBean.inStroreLowerList = viewModel.inStoreLowerList
                lowerAdapter.setListData(newBean.getLowerList() as MutableList<LowerListBean>, true)

                binding.expandableListView.expandGroup(0)
            }
        })
        viewModel.uc.clearFacilityListEvent.observe(this, {
            clearFacilityList()
        })
        viewModel.uc.clearLowerListEvent.observe(this, {
            clearLowerList()
        })
        viewModel.uc.choiceFacilityTypeEvent.observe(this, {
            ListSheetDialogFragment.showBottomSheet(
                parentFragmentManager,
                FacilityTypeList
            ) {
                if (it == 0) {//选择固定资产
                    viewModel.isScan.set(true)
                    binding.expandableListView.visibility = View.GONE
                    binding.ryCommon.visibility = View.VISIBLE
                    clearLowerList()
                } else {// 选择低耗
                    viewModel.isScan.set(false)
                    binding.ryCommon.visibility = View.GONE
                    binding.expandableListView.visibility = View.VISIBLE
                    clearFacilityList()
                }
                viewModel.facilityTypeStr.set(FacilityTypeList[it])
                viewModel.entityBean.facilityType = it
            }
        })
        viewModel.uc.choiceOwnerCompanyListEvent.observe(this, {
            if (it.list != null) {
                ownerCompanyList.clear()
                ownerCompanyList.addAll(it.list!!)
                for (bean in ownerCompanyList) {
                    ownerCompanyNameList.add(bean.companyShortName!!)
                }
            }
        })
        viewModel.uc.choiceOwnerCompanyEvent.observe(this, {
            ListSheetDialogFragment.showBottomSheet(
                parentFragmentManager,
                ownerCompanyNameList
            ) {
                viewModel.ownerCompanyStr.set(ownerCompanyNameList[it])
                var comBean = ownerCompanyList[it]
                viewModel.entityBean.parentCompanyId = comBean.companyId
            }
        })
    }
    fun addChildFile() {
        ChoiceImgHelper.ChoiceImg(this,
            { result -> result[0]?.let { t -> viewModel.uploadHeadImg(t.compressPath,
                AssetHandleApplyAddViewModel.ADAPTER_IMG
            ) } },
            {})
    }

    fun deleteSelectInfo(positon: Int, type: Int) {
        if (type.equals(0)) {
            viewModel.facilityList.removeAt(positon)
            setFacilityIdList()
            mAdapter.setList(viewModel.facilityList)
        }
    }
    fun deleteSortInfo (sortBean: AssetHandleSortBean) {
        if (sortBean.handleSelectType == "inuse") {
            for (bean in viewModel.inUseLowerList){
                if (bean.sortId == sortBean.sortId){
                    viewModel.inUseLowerList.remove(bean)
                    break
                }
            }
        } else {
            for (bean in viewModel.inStoreLowerList){
                if (bean.sortId == sortBean.sortId && bean.storehouseId == sortBean.storehouseId){
                    viewModel.inUseLowerList.remove(bean)
                    break
                }
            }
        }
    }

    fun setSortInfo (sort:AssetHandleSortBean?):AssetHandleSortBean?  {
        if (sort == null) {
            return sort
        }
        var assetCount = 0
        var locationDesc = ""
        var totalPrice: Double = 0.0
        var lossesNum = 0
        var badMap: HashMap<Int,Int> = hashMapOf()
        for (item1 in sort.locatList!!){
            totalPrice += item1.assetCount!! * item1.price!!
            assetCount += item1.assetCount!!
            if (item1.damageId!=null && item1.damageId!!> 0) {
                if (item1.storehouseLocatId == 0) {
                    lossesNum += item1.assetCount!!
                } else {
                    if (badMap.get(item1.storehouseLocatId)!=null) {
                        badMap.put(item1.storehouseLocatId!!, badMap.get(item1.storehouseLocatId)!! + item1.assetCount!!)
                    } else {
                        badMap.put(item1.storehouseLocatId!!, item1.assetCount!!)
                    }
                }
            } else if (item1.inventoryId!=null && item1.inventoryId!!>0) {
                if (badMap.get(item1.storehouseLocatId)!=null) {
                    badMap.put(item1.storehouseLocatId!!, badMap.get(item1.storehouseLocatId)!! + item1.assetCount!!)
                } else {
                    badMap.put(item1.storehouseLocatId!!, item1.assetCount!!)
                }
            } else {
                locationDesc += ',' + item1.locationDesc!! + '(' + item1.assetCount + ')'
            }
        }
        sort.assetCount = assetCount
        for (locatId in badMap.keys){
            var locatJson:SortLocatList? = null
            for (obj in sort.locatList!!) {
                if (obj.storehouseLocatId == locatId) {
                    locatJson = obj
                    break
                }
            }
            if (locatJson!=null){
                locationDesc += ',' + locatJson.locationDesc!! + '(' + badMap.get(locatId) + ')'
            }
        }
        if (lossesNum > 0) {
            locationDesc += ",丢失" + "(" + lossesNum + ")"
        }
        sort.locationDesc = locationDesc.substring(1)
        BigDecimal(totalPrice).divide(BigDecimal(assetCount),2)
        sort.price = BigDecimal(totalPrice).divide(BigDecimal(assetCount),2).toDouble()
        return sort
    }
    fun getSortBeanInfo (sortId: Int,storehouseId:Int):AssetHandleSortBean? {
        var sort:AssetHandleSortBean?=null
        for (oldBean in viewModel.inStoreLowerList){
            if (oldBean.sortId == sortId && oldBean.storehouseId == storehouseId) {
                sort = oldBean
                break
            }
        }
        return sort
    }
    fun addInStoreSortInfo (sortList: MutableList<AssetHandleSortBean>) {
        for (item in sortList){
            var sort = getSortBeanInfo(item.sortId!!,item.storehouseId!!)
            if (sort!=null) {
                var locat:SortLocatList? = null
                for (obj in sort.locatList){
                    if ((item.storehouseLocatId == obj.storehouseLocatId || item.handleStorehouseId == obj.storehouseLocatId)
                        && obj.damageId ==0 && obj.inventoryId == 0){
                        locat = obj
                        break
                    }
                }
                if (locat!=null) {
                    locat.assetCount = item.assetCount!!
                } else {
                    var newLocat = SortLocatList(
                        item.price!!,
                        item.stockNum,
                        item.assetCount!!,
                        item.storehouseLocatId,
                        item.storehouseLocatName!!,
                        0,
                        0
                    )
                    sort.locatList.add(newLocat)
                }
                setSortInfo(sort)
            } else{
                var newLocat = SortLocatList(
                    item.price,
                    item.stockNum,
                    item.assetCount,
                    item.storehouseLocatId,
                    item.storehouseLocatName,
                    0,
                    0
                )
                var newBean = AssetHandleSortBean()
                newBean.sortId = item.sortId
                newBean.sortCode = item.sortCode
                newBean.sortNo = item.sortCode
                newBean.sortName = item.sortName
                newBean.sortModel = item.sortModel
                newBean.model = item.sortModel
                newBean.price = item.price
                newBean.assetCount = item.assetCount
                newBean.storehouseId = item.storehouseId
                newBean.houseStoreName = item.houseStoreName
                newBean.locationDesc = item.locationDesc + "(" + item.assetCount + ")"
                newBean.locatList = arrayListOf<SortLocatList>(newLocat)
                viewModel.inStoreLowerList.add(newBean)
            }
        }
    }
    fun addDamageSortInfo (sortList: MutableList<AssetHandleSortBean>) {
        viewModel.inDamageLowerIdList.clear()
        for (item in sortList){
            viewModel.inDamageLowerIdList.add("" + item.sortId + "_" + item.storehouseId)
            var sort = getSortBeanInfo(item.sortId!!,item.storehouseId!!)
            for(item1 in item.sortList){
                if (item1.lossesNum !=null && item1.lossesNum!! > 0) {
                    if (sort!=null) {
                        var locatLosses:SortLocatList? = null
                        for (obj in sort.locatList){
                            if (obj.storehouseLocatId == 0 && obj.damageId == item1.damageId){
                                locatLosses = obj
                                break
                            }
                        }
                        if (locatLosses!=null) {
                            locatLosses.assetCount = item1.lossesNum!! + locatLosses.assetCount!!
                        } else {
                            var newLocat = SortLocatList(
                                item1.price?.toDouble(),
                                item1.lossesNum,
                                item1.lossesNum,
                                0,
                                "丢失",
                                0,
                                item1.damageId
                            )
                            sort.locatList.add(newLocat)
                        }
                    } else {
                        var newLocat = SortLocatList(
                            item1.price?.toDouble(),
                            item1.lossesNum,
                            item1.lossesNum,
                            0,
                            "丢失",
                            0,
                            item1.damageId
                        )
                        sort = AssetHandleSortBean()
                        sort.sortId =item1.sortId
                        sort.sortCode = item1.sortCode
                        sort.sortNo = item1.sortCode
                        sort.sortName = item1.sortName
                        sort.sortModel = item1.sortModel
                        sort.model = item1.sortModel
                        sort.price = item1.price?.toDouble()
                        sort.assetCount = item1.lossesNum
                        sort.storehouseId = item1.storehouseId
                        sort.houseStoreName = item1.storehouseName
                        sort.locationDesc ="丢失(" + item1.lossesNum + ")"
                        sort.locatList= arrayListOf(newLocat)
                        viewModel.inStoreLowerList.add(sort)
                    }
                }
                if (item1.badNum !=null && item1.badNum!! > 0) {
                    if (sort!=null) {
                        var locat:SortLocatList? = null
                        for (obj in sort.locatList){
                            if ((item.storehouseLocatId === obj.storehouseLocatId || item.handleStorehouseId === obj.storehouseLocatId) && obj.damageId === item1.damageId){
                                locat = obj
                                break
                            }
                        }
                        if (locat!=null) {
                            locat.assetCount = item1.badNum!! + locat.assetCount!!
                        } else {
                            var newLocat = SortLocatList(
                                item1.price?.toDouble(),
                                item1.badNum,
                                item1.badNum,
                                item1.storehouseLocatId,
                                item1.storehouseLocatName + "-坏",
                                0,
                                item1.damageId
                            )
                            sort.locatList.add(newLocat)
                        }
                    } else {
                        var newLocat = SortLocatList(
                            item1.price?.toDouble(),
                            item1.lossesNum,
                            item1.lossesNum,
                            item1.storehouseLocatId,
                            item1.storehouseLocatName + "-坏",
                            0,
                            item1.damageId
                        )
                        sort = AssetHandleSortBean()
                        sort.sortId =item1.sortId
                        sort.sortCode = item1.sortCode
                        sort.sortNo = item1.sortCode
                        sort.sortName = item1.sortName
                        sort.sortModel = item1.sortModel
                        sort.model = item1.sortModel
                        sort.price = item1.price?.toDouble()
                        sort.assetCount = item1.badNum
                        sort.storehouseId = item1.storehouseId
                        sort.houseStoreName = item1.storehouseName
                        sort.locationDesc =item1.storehouseLocatName + "-坏(" + item1.badNum + ")"
                        sort.locatList= arrayListOf(newLocat)
                        viewModel.inStoreLowerList.add(sort)
                    }
                }
            }
            setSortInfo(sort)
        }
    }
    fun addInvenSortInfo (sortList: MutableList<AssetHandleSortBean>) {

        viewModel.inInventoryLowerIdList.clear()
        for (item in sortList) {
            viewModel.inInventoryLowerIdList.add("" + item.sortId + "_" + item.storehouseId)
            var sort = getSortBeanInfo(item.sortId!!, item.storehouseId!!)
            for(item1 in item.sortList){
                if (sort!=null) {

                    var locat:SortLocatList? = null
                    for (obj in sort.locatList){
                        if ((item.storehouseLocatId === obj.storehouseLocatId || item.handleStorehouseId === obj.storehouseLocatId) && obj.inventoryId === item1.inventoryId){
                            locat = obj
                            break
                        }
                    }
                    if (locat!=null) {
                        locat.assetCount = item1.lossesNum!! + locat.assetCount!!
                    } else {
                        var newLocat = SortLocatList(
                            item1.price?.toDouble(),
                            item1.stockNum,
                            item1.lossesNum,
                            item1.storehouseLocatId,
                            item1.storehouseLocatName ,
                            item1.inventoryId,
                            0
                        )
                        sort.locatList.add(newLocat)
                    }
                } else {
                    var newLocat = SortLocatList(
                        item1.price?.toDouble(),
                        item1.stockNum,
                        item1.lossesNum,
                        item1.storehouseLocatId,
                        item1.storehouseLocatName ,
                        item1.inventoryId,
                        0
                    )
                    sort = AssetHandleSortBean()
                    sort.sortId= item1.sortId
                    sort.sortCode= item1.sortCode
                    sort.sortNo= item1.sortCode
                    sort.sortName= item1.sortName
                    sort.sortModel= item1.sortModel
                    sort.model= item1.sortModel
                    sort.price= item1.price?.toDouble()
                    sort.assetCount= item1.lossesNum
                    sort.storehouseId= item1.storehouseId
                    sort.houseStoreName= item1.storehouseName
                    sort.locationDesc= item1.storehouseLocatName + "(" + item1.lossesNum + ")"
                    sort.locatList= arrayListOf(newLocat)
                    viewModel.inStoreLowerList.add(sort)
                }
            }
            setSortInfo(sort)
        }
    }

    fun setFacilityIdList() {
        val facilityIdList: ArrayList<Int> = arrayListOf()
        for (bean in viewModel.facilityList) {
            facilityIdList.add(bean.id!!)
        }
        viewModel.facilityIdList = facilityIdList
        if (facilityIdList.isNotEmpty()) {
            viewModel.facilityIdNum.set("（" + facilityIdList.size + "）")
        } else {
            viewModel.facilityIdNum.set("")
        }
    }
    fun setProductIdList() {
        val productIdList: ArrayList<Int> = arrayListOf()
        for (bean in viewModel.inUseProductList) {
            productIdList.add(bean.productId!!)
        }
        for (bean in viewModel.inStoreProductList) {
            productIdList.add(bean.productId!!)
        }
        viewModel.productIdList = productIdList
    }
    fun setSortIdInfoList () {
        val sortIdInfoList: HashMap<String, Int> = hashMapOf()
        for (bean in viewModel.inUseLowerList) {
            sortIdInfoList.put("0##" + bean.sortId,bean.assetCount!!)
        }
        for (bean in viewModel.inStoreLowerList) {
            sortIdInfoList.put(""+bean.storehouseId + "##"+bean.sortId,bean.assetCount!!)
        }
        viewModel.sortIdInfoList = sortIdInfoList
    }

    fun clearFacilityList() {
        viewModel.facilityList.clear()
        mAdapter.setList(viewModel.facilityList)
        setFacilityIdList()
    }

    fun clearLowerList() {
        viewModel.inUseLowerList.clear()
        viewModel.inStoreLowerList.clear()
        viewModel.inUseProductList.clear()
        viewModel.inStoreProductList.clear()
        lowerAdapter.setListData(arrayListOf(), true)
    }
}